/*
 * stimer.c
 *
 *  Created on: 2020-12-31
 *      Author: chenss
 */

#include "stimer.h"

#define TIMx TIM6
#define COUNTER_CLK 200000UL

static uint32_t _tick;

void STimer_Init(void)
{
      LL_TIM_InitTypeDef TIM_InitStruct = {0};

      /* Peripheral clock enable */
      LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM6);

      /* TIM7 interrupt Init */
      NVIC_SetPriority(TIM6_DAC_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(),2, 0));
      NVIC_EnableIRQ(TIM6_DAC_IRQn);

      TIM_InitStruct.Prescaler = (uint16_t)((SystemCoreClock / (2 * COUNTER_CLK)) - 1);
      TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
      TIM_InitStruct.Autoreload = (uint16_t)((COUNTER_CLK / STIMER_FREQ) - 1);
      LL_TIM_Init(TIMx, &TIM_InitStruct);

      LL_TIM_ClearFlag_UPDATE(TIMx);
      LL_TIM_EnableIT_UPDATE(TIMx);

      LL_TIM_SetCounter(TIMx, 0);
      LL_TIM_EnableCounter(TIMx);
}

void TIM6_DAC_IRQHandler(void)
{
    if(LL_TIM_IsActiveFlag_UPDATE(TIMx))
    {
        LL_TIM_ClearFlag_UPDATE(TIMx);
        _tick ++;
    }
}

uint32_t STimer_Tick(void)
{
    uint32_t tick;

    do
    {
        tick = _tick;
    }while(tick != _tick);

    return tick;
}
